<template>
  <div id="app">

    <!-- 新增表单 -->
    <el-dialog title="出库申请" :visible.sync="addFormView">
      <el-form label-position="left" label-width="80px" :model="add">
        <el-form-item label="商品">
          <el-select v-model="add.goodsId" placeholder="请选择商品">
            <el-option v-for="item in goodsOptions"
                       :key="item.goodsId"
                       :label="item.goodsName"
                       :value="item.goodsId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="销售数量">
          <el-input-number size="small" :min="1" v-model.number="add.saleCount"></el-input-number>
        </el-form-item>
        <el-form-item label="库存">
          <el-input size="small" v-model="stock" disabled></el-input>
        </el-form-item>
<!--        <el-form-item label="销售单价">-->
<!--          <el-input v-model="add.price" placeholder="进货单价" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="总价">-->
<!--          <el-input v-model="addTotalPrice" disabled></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormView = false">取 消</el-button>
        <el-button type="primary" @click="submitAddForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改表单 -->
    <el-dialog title="修改" :visible.sync="updateFormView">
      <el-form label-position="left" label-width="80px" :model="update">
        <el-form-item v-if="update.backReason" label="驳回原因">
          {{ update.backReason }}
        </el-form-item>
        <el-form-item label="商品名">
          <el-input v-model="update.goodsName" :disabled="update.status === 2 || update.empId !== userId"></el-input>
        </el-form-item>
        <el-form-item label="商品数量">
          <el-input-number :disabled="update.status === 2 || update.empId !== userId" size="small" min="1"
                           v-model.number="update.saleCount"></el-input-number>
        </el-form-item>
<!--        <el-form-item label="进货单价">-->
<!--          <el-input v-model="update.price" :disabled="update.empId !== userId" placeholder="进货单价" autocomplete="off"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="总价">-->
<!--          <el-input v-model="updateTotalPrice" :disabled="update.status === 2 || update.empId !== userId"></el-input>-->
<!--        </el-form-item>-->
      </el-form>
      <template #footer>
        <el-button @click="updateFormView = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdateForm">确 定</el-button>
        <el-button v-show="userType === 9" type="success" @click="submitPass">通过审核</el-button>
        <el-button v-show="userType === 9" type="danger" @click="submitBack">驳回</el-button>
      </template>
      <el-dialog append-to-body title="驳回原因" :visible.sync="backFormView">
        <el-form ref="backForm" label-position="left" label-width="80px" :model="update" :rules="rules">
          <el-form-item label="驳回原因" prop="backReason">
            <el-input type="textarea" v-model="update.backReason" placeholder="驳回原因" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="backFormView = false">取 消</el-button>
          <el-button type="primary" @click="submitBackForm('backForm')">确 定</el-button>
        </template>
      </el-dialog>
    </el-dialog>

    <!-- 搜索框 -->
    <el-card class="box-card" shadow="always">
      <el-input
        placeholder="商品名"
        v-model="selectSale.goodsName"
        size="medium">
      </el-input>
      <el-input
        placeholder="申请人"
        v-model="selectSale.name"
        size="medium">
      </el-input>
      <el-button type="info" size="medium" @click="getSaleList" plain>查询</el-button>
      <el-button type="warning" size="medium" @click="handelRecet" plain>重置</el-button>
    </el-card>
    <el-card class="box-card" shadow="always">
      <el-button type="primary" size="medium" @click="addFormView = true" plain>申请出库</el-button>
    </el-card>

    <!-- 表格以及分页 -->
    <el-card shadow="always">
      <el-table
        :data="tableData"
        style="width: 100%"
        height="415">
        <el-table-column
          label="商品名"
          width="100"
          prop="goodsName">
        </el-table-column>
        <el-table-column
          label="图片"
          align="center"
          width="100">
          <template slot-scope="scope">
            <el-image
              :src="scope.row.goodsImg"
              fit="fit">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          label="申请人"
          width="180"
          align="center"
          prop="name">
        </el-table-column>
        <el-table-column
          label="出库数量"
          width="100"
          align="center"
          prop="saleCount">
        </el-table-column>
        <el-table-column
          label="物品单价"
          width="100"
          align="center"
          prop="price">
        </el-table-column>
        <el-table-column
          label="物品总价"
          width="100"
          align="center"
          prop="totalPrice">
        </el-table-column>
        <el-table-column
          label="销售日期"
          prop="saleDate">
        </el-table-column>
        <el-table-column
          label="申请状态"
          prop="status">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="warning">待审核</el-tag>
            <el-tag v-if="scope.row.status === 2" type="success">已领取</el-tag>
            <el-tag v-if="scope.row.status === 0" type="danger">已驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <div v-if="scope.row.totalPrice >= 1000 && scope.row.status === 2 && userType !== 1">
              <el-button
                type="success"
                size="mini"
                slot="reference"
                @click="handelDelete(scope.row)">
                归还
              </el-button>
              <el-button
                type="danger"
                size="mini"
                slot="reference"
                @click="handelDistory(scope.row)">
                报废
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>

    </el-card>
  </div>

</template>

<script>
// eslint-disable-next-line no-unused-vars
import { Message, MessageBox } from 'element-ui'
import {getGoodsAndStock, saleGoods, updateSaleInfo, deleteSaleInfo, passSaleApi, deleteSaleById} from '@/api/sale'
import instance from '@/utils/request'

export default {
  name: 'SalePage',
  data () {
    return {
      input1: '',
      input2: '',
      formLabelWidth: '80px',
      stock: 0, // 库存
      add: {
        goodsId: '',
        saleCount: '',
        price: '',
        totalPrice: ''
      },
      update: {
        goodsId: '',
        saleCount: '',
        price: '',
        totalPrice: ''
      },
      selectSale: {
        name: '',
        goodsName: '',
        empId: ''
      },
      updateFormView: false, // 修改表单显示
      addFormView: false, // 新增表单显示
      currentPage: 1, // 当前页
      pageSize: 5,
      total: 1,
      tableData: [],
      goodsOptions: [],
      rules: {
        backReason: [
          {
            required: true,
            message: '请输入驳回原因',
            trigger: 'blur'
          }
        ]
      },
      backForm: null,
      backFormView: false // 驳回表单显示
    }
  },

  methods: {
    async submitPass () {
      if (this.update.status !== 1) {
        Message.error('只能通过待审核的申请！')
        return
      }
      this.update.backReason = ''
      const res = await passSaleApi(this.update.id)
      Message.success(res.data)
      await this.getSaleList()
      this.updateFormView = false
    },
    submitBack () {
      if (this.update.status !== 1) {
        Message.error('只能驳回待审核的申请！')
        return
      }
      this.backFormView = true
    },
    async submitBackForm (formName) {
      await this.$refs[formName].validate()
      // await this.backForm.validate()
      this.update.status = 0
      await updateSaleInfo(this.update)
      Message.success('驳回成功！')
      await this.getSaleList()
      this.backFormView = false
      this.updateFormView = false
    },
    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pageSize = val
      this.getSaleList()
    },
    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getSaleList()
    },
    handleEdit (row) {
      this.updateFormView = true
      this.update = row
    },
    // 查询重置
    handelRecet () {
      this.selectSale = {
        name: '',
        goodsName: ''
      }
      this.getSaleList()
    },
    // 删除
    handelDelete (row) {
      let message = ''
      if (row.status === 2) {
        message = '确定归还该物品？将会退回到库存中'
      } else {
        message = '确定删除该出库信息?'
      }
      const this_ = this
      MessageBox.confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteSaleInfo(row.id)
        // await this.getSaleList()
        Message({
          type: 'success',
          message: '归还成功!'
        })
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消归还'
        })
      }).finally(async () => {
        await this_.getSaleList()
      })
    },
    handelDistory (row) {
      const this_ = this
      MessageBox.confirm('确定报废该条出库记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deleteSaleById(row.id)
        Message({
          type: 'success',
          message: '报废成功!'
        })
      }).catch(() => {
        Message({
          type: 'info',
          message: '已取消报废'
        })
      }).finally(async () => {
        await this_.getSaleList()
      })
    },
    async submitAddForm () {
      this.add.totalPrice = this.addTotalPrice
      await saleGoods(this.add)
      Message.success('申请成功!')
      await this.getSaleList()
      this.addFormView = false
    },
    // 提交修改表单
    async submitUpdateForm () {
      this.update.status = 1
      this.update.backReason = ''
      this.updateFormView = false
      await updateSaleInfo(this.update)
      Message.success('修改成功!')
      await this.getSaleList()
    },
    // 查询销售订单
    async getSaleList () {
      if (this.userType === 1) {
        this.selectSale.empId = this.userId
      }
      const res = await instance.post(`/sale/list/${this.currentPage}/${this.pageSize}`,
        this.selectSale)
      this.tableData = res.data.list
      this.total = res.data.total
    },
    // 获取商品列表
    async getGoodsOption () {
      const res = await getGoodsAndStock()
      this.goodsOptions = res.data
    },
    getStock (id) {
      const foundItem = this.goodsOptions.find(item => item.goodsId === id)
      this.stock = foundItem.goodsCount
    }
  },

  created () {
    this.getGoodsOption()
    this.getSaleList()
  },

  computed: {
    addTotalPrice () {
      return (this.add.saleCount * this.add.price).toFixed(2)
    },
    updateTotalPrice () {
      return (this.update.saleCount * this.update.price).toFixed(2)
    },
    userType () {
      return this.$store.getters.userType
    },
    userId () {
      return this.$store.getters.id
    }
  },

  watch: {
    'add.goodsId' (newValue) {
      this.getStock(newValue)
    }
  }

}
</script>

<style scoped>
.el-input {
  width: 200px;
  margin-right: 5px;
}

.el-card ::v-deep .el-card__body {
  padding: 10px;
}

.el-pagination {
  padding: 15px;
}
</style>
